<script setup lang="ts">
  import { User, Lock } from '@element-plus/icons-vue'
  import { ref, watch } from 'vue'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { useRouter } from 'vue-router'
  import { userRegisterService, userLoginService } from '@/api/user'
  import { useUserStore } from '@/stores/modules/user'
  import { storeToRefs } from 'pinia'
  const userStore = useUserStore()
  const router = useRouter()
  // 使用 storeToRefs 来保持响应式并正确推断类型
  const { IsRemember } = storeToRefs(userStore)

  interface RuleForm {
    username: string
    password: string
    confirmPassword: string
  }
  const isRegister = ref<boolean>(false)
  const formModel = ref<RuleForm>({
    username: '',
    password: '',
    confirmPassword: ''
  })
  const rules:FormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { pattern: /^\S{6,15}$/, message: '长度在 6 到 15 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      { pattern: /^\S{6,15}$/, message: '长度在 6 到 15 个字符', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== formModel.value.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
  const form = ref<FormInstance>()
  const register = async () => {
    if(form.value){
      await form.value.validate()
      const res = await userRegisterService(formModel.value)
      if (res.data.error_code ) {
        console.log('注册成功', res.data)
        ElMessage.success('注册成功')
        isRegister.value = false
      } else {
        // 处理注册失败的情况（如用户名已存在）
        ElMessage.error(res.data.message || '注册失败')
      }
    }
    
  }
  const login = async () => {
      if(form.value){
        await form.value.validate()
        const res = await userLoginService({
          username:formModel.value.username,
          password:formModel.value.password
      })
      const { access_token, refresh_token } = res.data.data
      userStore.setToken(access_token)
      userStore.setRememberMe(IsRemember.value)
      if (IsRemember.value) {
        // access_token存sessionStorage，refresh_token存localStorage
        sessionStorage.setItem('access_token', access_token)
        localStorage.setItem('refresh_token', refresh_token)
        localStorage.setItem('username', formModel.value.username)
      } else {
        // 都存sessionStorage，浏览器关闭后清除
        sessionStorage.setItem('access_token', access_token)
        sessionStorage.setItem('refresh_token', refresh_token)
      }
      ElMessage.success('登录成功')
      router.push('/')
    }
  }
  watch(isRegister,()=>{
    formModel.value = {
      username:'',
      password:'',
      confirmPassword:''
    }
  })
  
  // const testConnection = async () => {  //测试后端连接
  //   try {
  //     const response = await fetch('http://127.0.0.1:4523/m1/7387680-7120109-default')
  //     alert(`后端服务状态: ${response.status}`)
  //   } catch (error) {
  //     alert('后端服务未运行，请启动后端服务')
  //   }
  // }
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form"  >
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :rules="rules" :model="formModel">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" v-model="formModel.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :prefix-icon="Lock"
            v-model="formModel.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            :prefix-icon="Lock"
            v-model="formModel.confirmPassword"
            type="password"
            placeholder="请输入再次密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <el-form ref="form" size="large" autocomplete="off" v-else :rules="rules" :model="formModel">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="formModel.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            v-model="formModel.password"
          ></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="IsRemember">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
            <!-- <button @click="testConnection">测试后端连接</button> -->
          </div>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
  .login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
      background:
      url('@/assets/loginBg.jpg') no-repeat center / cover;
      border-radius: 0 20px 20px 0;
      transform: scale(1.02); // 避免虚化边缘留白
    }
    .form {
      display: flex;
      flex-direction: column;
      justify-content: center;
      user-select: none;
      .title {
        margin: 0 auto;
      }
      .button {
        width: 100%;
      }
      .flex {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
    }
  }
</style>